package models

import (
	db "blogtemp/database"
	"log"
	"strconv"
	//"fmt"
)

//Ali_setting 设置
type Ali_setting struct {
	Id    int    `json:"sId" form:"sId"`
	Key   string `json:"key" form:"key"`
	Value string `json:"value" form:"value"`
}

// GetMyInfosAndViewNum 获取个人信息
func GetMyInfosAndViewNum() (infos []Ali_setting) {
	datas, err := db.SqlDB.Query("select `key`,`value` from ali_setting where `key`='qq' or `key` = 'email' or `key` = 'viewNum'")
	if err != nil {
		log.Println(err)
	}
	defer datas.Close()
	for datas.Next() {
		var uInfo Ali_setting
		datas.Scan(&uInfo.Key, &uInfo.Value)
		infos = append(infos, uInfo)
	}
	if err = datas.Err(); err != nil {
		return nil
	}
	views := GetViewsNum()
	infos = append(infos, *views)
	return infos
}

// GetViewsNum 获取浏览次数
func GetViewsNum() (view *Ali_setting) {
	var viewNum Ali_setting
	err := db.SqlDB.QueryRow("select `sid`,`key`,`value` from ali_setting where `key` = 'viewNum'").Scan(&viewNum.Id, &viewNum.Key, &viewNum.Value)
	if err != nil {
		log.Println(err)
	}
	temp, err := strconv.Atoi(viewNum.Value)
	temp++
	viewNum.Value = strconv.Itoa(temp)
	// log.Print(viewNum.Value)
	_, err = db.SqlDB.Exec("update ali_setting set value = ? where sid = ?", viewNum.Value, viewNum.Id)
	if err != nil {
		log.Println(err)
	}
	return &viewNum
}

// GetFriendlyUrls 获取友链
func GetFriendlyUrls() (urlinfo *Ali_setting) {
	var friendlyurls Ali_setting
	err := db.SqlDB.QueryRow("select `value` from ali_setting where `key` = 'friendlyurl'").Scan(&friendlyurls.Value)
	if err != nil {
		log.Fatalln(err)
	}
	return &friendlyurls
}
